import { ref, watch, h, onMounted } from "vue";
import { DynamicFormExpose, FormItemComponentType, FormItemData } from "../../CURDDialog/models";
import { getDictionaryByType } from "/@/api/aiot/dictionary";
import { DispatchWorkOrderItem, WorkOrderItem } from "/@/api/aiot/serviceApply/models";
import { mapperWorkStateFunction } from "/@/api/aiot/serviceWorkOrder";
import {
  CompleteWorkOrder,
  FunctionMapperItem,
  SignInWorkOrder,
  VisitRecordItem,
  WorkOrderConstruction,
  WorkOrderInfo,
  WorkRoleType,
} from "/@/api/aiot/serviceWorkOrder/models";
import { RegionsItem } from "/@/api/aiot/zone/models";
import type { TableRecord } from "/@/api/models";
import SelectInput from "/@/components/common/SelectInput.vue";
import SelectUser from "/@/components/common/SelectUser.vue";
import CompleteRadio from "./CompleteRadio.vue";
import { useI18n } from "/@/locales/useI18n";
import dayjs, { Dayjs } from "dayjs";

export function useOrderModal() {
  const { t } = useI18n();
  const visitRecordIns = ref<DynamicFormExpose>();
  const selectedUserIds = ref<Array<string>>(["bad4b3a8-21b9-4834-9338-93d4b7a7bcd9"]);
  const signinIns = ref<DynamicFormExpose>();
  const columns = ref<Array<TableRecord>>([
    {
      title: t("aiot.serviceOrder.workOrderCode"),
      dataIndex: "workOrderCode",
      width: 100,
    },
    {
      title: t("aiot.serviceOrder.workOrderTypeName"),
      dataIndex: "workOrderTypeName",
      width: 100,
    },
    {
      title: t("aiot.serviceOrder.projectName"),
      dataIndex: "projectName",
      width: 100,
    },
    {
      title: t("aiot.serviceOrder.contactsPerson"),
      dataIndex: "contactsPerson",
      width: 100,
    },
    {
      title: "联系地址",
      dataIndex: "address",
      width: 120,
    },
    {
      title: t("aiot.serviceOrder.expectedTime"),
      dataIndex: "plannTime",
      width: 100,
      sorter: true,
    },
    {
      title: t("aiot.serviceOrder.workOrderStateName"),
      dataIndex: "workOrderStateName",
      width: 100,
    },

    {
      title: t("common.oper"),
      key: "oper",
      fixed: "right",
      width: 100,
    },
  ]);
  const dispatchModel = ref<DispatchWorkOrderItem>({
    operationUserName: "",
    helperUserName: "",
    operationUserId: "",
    helperUserIds: [],
    plannTime: "",
    opinion: "",
  });
  const visitRecordModel = ref<VisitRecordItem>({
    visitRecordTitle: "",
    visitRecordContent: "",
    visitRecordSuggestion: "",
    workOrderVisitRecordType: "",
  });

  const constructionModel = ref<WorkOrderConstruction>({
    failureReason: [],
    maintenanceType: "",
    maintenanceContent: "",
    constructionBeforeImages: [],
    constructionAfterImages: [],
    constructionAppendixs: [],
  });
  const completeModel = ref<CompleteWorkOrder>({
    completionSituation: "",
    completedAppendix: [],
    completedRemarks: "",
  });
  const signinModel = ref<SignInWorkOrder>({
    signInAddress: "",
    latitude: "",
    longitude: "",
  });
  const locDgVisible = ref<boolean>(false);
  function chooseLoc(e: RegionsItem) {
    signinModel.value.latitude = e.latitude as string;
    signinModel.value.longitude = e.longitude as string;
    signinModel.value.signInAddress = e.formattedAddress;
  }
  const disabledDate = (current: Dayjs) => {
    return current && current < dayjs().startOf("day");
  };
  const visitRecordModelFormSetting = ref<Array<FormItemData>>([
    {
      key: "visitRecordTitle",
      label: t("aiot.serviceOrder.visitRecordTitle"),
      max: 32,
      required: true,
      // pattern: PatternKey.name,
    },
    {
      key: "visitRecordContent",
      label: t("aiot.serviceOrder.visitRecordContent"),
      type: FormItemComponentType.TEXTAREA,
      max: 250,
      // pattern: PatternKey.name,
      required: true,
    },
    {
      key: "visitRecordSuggestion",
      label: t("aiot.serviceOrder.visitRecordSuggestion"),
      type: FormItemComponentType.TEXTAREA,
      max: 250,
      // pattern: PatternKey.name,
      required: true,
    },
    {
      key: "workOrderVisitRecordType",
      hide: true,
    },
  ]);
  const signinModelFormSetting = ref<Array<FormItemData>>([
    {
      label: t("aiot.serviceOrder.signInAddress"),
      key: "signInAddress",
      required: true,
      max: 256,
      // type: FormItemComponentType.TEXTAREA,
      customComponent: h(SelectInput, {
        onClick() {
          locDgVisible.value = true;
        },
      }),
    },
    {
      key: "latitude",
      hide: true,
    },
    {
      key: "longitude",
      hide: true,
    },
  ]);
  const completeModelFormSetting = ref<Array<FormItemData>>([
    {
      key: "completionSituation",
      required: true,
      label: t("aiot.serviceOrder.completionSituation"),
      customComponent: h(CompleteRadio, {
        onClick(val) {
          completeModel.value.completionSituation = val;
        },
      }),
    },
    {
      key: "completedAppendix",
      label: t("aiot.serviceOrder.completedAppendix"),
      type: FormItemComponentType.IMGUPLOAD,
      props: {
        max: 6,
      },
      // pattern: PatternKey.name,
    },
    {
      key: "completedRemarks",
      label: t("aiot.serviceOrder.completedRemarks"),
      type: FormItemComponentType.TEXTAREA,
      props: {
        placeholder: t("common.pleaseInput"),
      },
      max: 250,
      // pattern: PatternKey.name,
    },
  ]);
  const constructionModelFormSetting = ref<Array<FormItemData>>([
    {
      key: "failureReason",
      label: t("aiot.serviceOrder.failureReason"),
      type: FormItemComponentType.SELECT,
      required: true,
      async getData() {
        let data = await getDictionaryByType({ dictionaryType: "FAILURECAUSE" });
        return data
          ? data.map((el) => ({
              label: el.dictionaryName,
              value: el.dictionaryCode,
            }))
          : [];
      },
      props: {
        mode: "multiple",
        options: [],
        getPopupContainer(node) {
          return node.parentNode;
        },
      },
    },
    {
      key: "maintenanceType",
      label: t("aiot.serviceOrder.maintenanceType"),
      required: true,
      type: FormItemComponentType.SELECT,
      async getData() {
        let data = await getDictionaryByType({ dictionaryType: "WORKWXTYPE" });
        return data
          ? data.map((el) => ({
              label: el.dictionaryName,
              value: el.dictionaryCode,
            }))
          : [];
      },
      props: {
        options: [],
        getPopupContainer(node) {
          return node.parentNode;
        },
      },
    },
    {
      key: "maintenanceContent",
      label: t("aiot.serviceOrder.maintenanceContent"),
      required: true,
      type: FormItemComponentType.TEXTAREA,
      max: 250,
      props: {
        placeholder: t("common.pleaseInput"),
      },
      // pattern: PatternKey.name,
    },
    {
      key: "constructionBeforeImages",
      label: t("aiot.serviceOrder.constructionBeforeImages"),
      type: FormItemComponentType.IMGUPLOAD,
      props: {
        max: 6,
      },
      // pattern: PatternKey.name,
    },
    {
      key: "constructionAfterImages",
      label: t("aiot.serviceOrder.constructionAfterImages"),
      type: FormItemComponentType.IMGUPLOAD,
      props: {
        max: 6,
      },
      // pattern: PatternKey.name,
    },
    {
      key: "constructionAppendixs",
      label: t("aiot.serviceOrder.constructionAppendixs"),
      type: FormItemComponentType.IMGUPLOAD,
      props: {
        max: 6,
      },
      // pattern: PatternKey.name,
    },
  ]);
  const selectUserMode = ref<"radio" | "checkbox">("radio");
  const chooseUserVisible = ref<boolean>(false);
  const chooseOperationUser = ref<boolean>(false);
  const dispatchModelFormSetting = ref<Array<FormItemData>>([
    {
      label: "工单负责人",
      key: "operationUserName",
      required: true,
      props: {
        placeholder: t("common.pleaseSelect"),
        mode: "radio",
        projectId: "",
      },
      customComponent: h(SelectUser, {
        onSelect(val) {
          dispatchModel.value.operationUserId = val[0].userId;
          dispatchModel.value.operationUserName = val[0].userName;
        },
      }),
    },
    {
      label: "工单协同人",
      key: "helperUserIds",
      props: {
        projectId: "",
        placeholder: "请选择(可多选)",
      },
      customComponent: h(SelectUser, {
        onChange(val, users) {
          let helpUserArr = users.map((item) => {
            return item.userName;
          });
          dispatchModel.value.helperUserName = helpUserArr.join("，");
        },
      }),
    },
    // {
    //   label: t("aiot.serviceApply.operationUser"),
    //   key: "operationUserName",
    //   required: true,
    //   props: {
    //     placeholder: t("common.pleaseSelect"),
    //   },
    //   // type: FormItemComponentType.TEXTAREA,
    //   customComponent: h(SelectInput, {
    //     onClick() {
    //       selectedUserIds.value = [dispatchModel.value.operationUserId || ""];
    //       selectUserMode.value = "radio";
    //       chooseOperationUser.value = true;
    //       chooseUserVisible.value = true;
    //     },
    //   }),
    // },
    // {
    //   label: t("aiot.serviceApply.helperUser"),
    //   key: "helperUserName",
    //   // type: FormItemComponentType.TEXTAREA,
    //   props: {
    //     placeholder: "请选择(可多选)",
    //   },
    //   customComponent: h(SelectInput, {
    //     onClick() {
    //       selectedUserIds.value = dispatchModel.value.helperUserIds || [];
    //       selectUserMode.value = "checkbox";
    //       chooseOperationUser.value = false;
    //       chooseUserVisible.value = true;
    //     },
    //   }),
    // },
    {
      label: t("aiot.serviceApply.plannTime"),
      key: "plannTime",
      required: true,
      type: FormItemComponentType.DATEPICKER,
      props: {
        showTime: { format: "HH:mm" },
        format: t("common.dateTimeFormatStr1"),
        valueFormat: t("common.dateTimeFormatStr1"),
        placeholder: t("common.pleaseSelect"),
        disabledDate: disabledDate,
      },
    },
    {
      label: t("aiot.serviceApply.opinion"),
      key: "opinion",
      max: 256,
      type: FormItemComponentType.TEXTAREA,
      props: {
        placeholder: t("common.pleaseInput"),
      },
    },
    {
      key: "operationUserId",
      hide: true,
    },
    {
      key: "helperUserName",
      hide: true,
    },
  ]);
  function handleSelectedUser({ userIds, selectedUsers }) {
    if (chooseOperationUser.value) {
      dispatchModel.value.operationUserId = userIds[0];
      dispatchModel.value.operationUserName = selectedUsers[0].userName;
    } else {
      dispatchModel.value.helperUserIds = userIds;
      let helpUserArr = selectedUsers.map((item) => {
        return item.userName;
      });
      dispatchModel.value.helperUserName = helpUserArr.join("，");
    }
  }
  interface TabItem {
    key: string;
    tabName: string;
    countKey: string;
    numberStyle: any;
  }

  const tabArr = ref<Array<TabItem>>([
    {
      key: "ALL",
      tabName: t("aiot.serviceOrder.ALL"),
      countKey: "workOrdersTotal",
      numberStyle: {
        backgroundColor: "rgba(75,139,244,0.10)",
        color: "#4B8BF4",
        boxShadow: "0 0 0 1px #4285F4 inset",
      },
    },
    {
      key: "DISPATCH",
      tabName: t("aiot.serviceOrder.DISPATCH"),
      countKey: "workOrdersDispatch",
      numberStyle: {
        backgroundColor: "rgba(245,109,106,0.10)",
        color: "#F56D6A",
        boxShadow: "0 0 0 1px #F56D6A inset",
      },
    },
    {
      key: "WAITING",
      tabName: t("aiot.serviceOrder.WAITING"),
      countKey: "workOrdersWaiting",
      numberStyle: {
        backgroundColor: "rgba(253,131,88,0.10)",
        color: "#FD8358",
        boxShadow: "0 0 0 1px #FD8358 inset",
      },
    },
    {
      key: "EXECUTE",
      tabName: t("aiot.serviceOrder.EXECUTE"),
      countKey: "workOrdersExecute",
      numberStyle: {
        backgroundColor: "rgba(57,201,225,0.10)",
        color: "#39C9E1",
        boxShadow: "0 0 0 1px #39C9E1 inset",
      },
    },
    {
      key: "OVER",
      tabName: t("aiot.serviceOrder.OVER"),
      countKey: "workOrdersOver",
      numberStyle: {
        backgroundColor: "rgba(245,184,60,0.10)",
        color: "#F5B83C",
        boxShadow: "0 0 0 1px #F5B83C inset",
      },
    },
    {
      key: "PROGRESS",
      tabName: t("aiot.serviceOrder.PROGRESS"),
      countKey: "workOrdersProgress",
      numberStyle: {
        backgroundColor: "rgba(75,139,244,0.10)",
        color: " #4B8BF4",
        boxShadow: "0 0 0 1px #4B8BF4 inset",
      },
    },
    {
      key: "FINISHED",
      tabName: t("aiot.serviceOrder.FINISHED"),
      countKey: "workOrdersFinished",
      numberStyle: {
        backgroundColor: "rgba(56,206,123,0.10)",
        color: "#38CE7B",
        boxShadow: "0 0 0 1px #38CE7B inset",
      },
    },
    {
      key: "CANCEL",
      tabName: t("aiot.serviceOrder.CANCEL"),
      countKey: "workOrdersCancel",
      numberStyle: {
        backgroundColor: "rgba(123,135,154,0.10)",
        color: "#7B879A",
        boxShadow: "0 0 0 1px #7B879A inset",
      },
    },
  ]);
  tabArr.value.forEach((el) => {
    Object.assign(el.numberStyle, {
      width: "40px",
      marginRight: "5px",
      fontSize: "14px",
      height: "24px",
      lineHeight: "24px",
    });
  });

  const btnFunctionMapper = ref<Array<FunctionMapperItem>>([]);
  onMounted(async () => {
    btnFunctionMapper.value = (await mapperWorkStateFunction()) || [];
  });
  function showBtnFn(workOrderItem: WorkOrderInfo, btnType, currentRole) {
    let isAdmin = currentRole === WorkRoleType.ADMIN ? true : false;
    let functionArr: FunctionMapperItem[] = btnFunctionMapper.value.filter((item) => {
      if (isAdmin) {
        return item.workState === workOrderItem.workOrderState && item.isAdmin === isAdmin;
      } else {
        return (
          item.workState === workOrderItem.workOrderState &&
          item.isAdmin === isAdmin &&
          workOrderItem.operationFlag === 1
        );
      }
    });
    return functionArr.length > 0 ? functionArr[0].functions.includes(btnType) : false;
  }
  return {
    selectedUserIds,
    selectUserMode,
    visitRecordIns,
    locDgVisible,
    chooseLoc,
    signinIns,
    handleSelectedUser,
    showBtnFn,
    tabArr,
    chooseUserVisible,
    columns,
    dispatchModel,
    dispatchModelFormSetting,
    constructionModel,
    constructionModelFormSetting,
    completeModel,
    completeModelFormSetting,
    signinModel,
    signinModelFormSetting,
    visitRecordModel,
    visitRecordModelFormSetting,
  };
}
